package com.my.bbs.controller.rest;

import com.my.bbs.common.Constants;
import com.my.bbs.common.ServiceResultEnum;
import com.my.bbs.entity.MyPost;
import com.my.bbs.entity.MyRole;
import com.my.bbs.entity.MyUser;
import com.my.bbs.entity.RecentCommentListEntity;
import com.my.bbs.service.*;
import com.my.bbs.util.*;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 86187
 */
@Controller
public class MyUserController {

    @Resource
    private MyRoleService roleService;

    @Resource
    private MyUserService myUserService;

    @Resource
    private MyEmailService emailService;

    @Resource
    private MyPostService myPostService;

    @Resource
    private MyPostCollectService myPostCollectService;

    @Resource
    private MyPostCommentService myPostCommentService;

    @GetMapping({"/login", "/login.html"})
    public String loginPage() {
        return "user/login";
    }

    @GetMapping({"/register", "/register.html"})
    public String registerPage() {
        return "user/reg";
    }

    @GetMapping("/userCenter/{userId}")
    public String userCenterPage(HttpServletRequest request, @PathVariable("userId") Long userId) {
        //基本用户信息
        MyUser myUser = myUserService.getUserById(userId);
        if (myUser == null) {
            return "error/error_404";
        }

        //近期发布的帖子
        List<MyPost> recentPostList = myPostService.getRecentPostListByUserId(userId);

        //近期回复的内容
        List<RecentCommentListEntity> recentCommentList = myPostCommentService.getRecentCommentListByUserId(userId);

        // 用户角色
        MyRole pageRole = roleService.getCodeById(myUser.getRoleId());


        request.setAttribute("myUser", myUser);
        request.setAttribute("pageRole", pageRole);
        request.setAttribute("recentPostList", recentPostList);
        request.setAttribute("recentCommentList", recentCommentList);
        return "user/home";
    }

    @GetMapping("/userSet")
    public String userSetPage(HttpServletRequest request) {
        MyUser currentUser = (MyUser) request.getSession().getAttribute(Constants.USER_SESSION_KEY);
        request.setAttribute("myUser", currentUser);
        return "user/set";
    }

    @GetMapping("/myCenter")
    public String myCenterPage(HttpServletRequest request) {

        //基本用户信息
        MyUser currentUser = (MyUser) request.getSession().getAttribute(Constants.USER_SESSION_KEY);

        //我发的贴
        List<MyPost> myPostList = myPostService.getMyPostList(currentUser.getUserId());
        int myBBSPostCount = 0;
        if (!CollectionUtils.isEmpty(myPostList)) {
            myBBSPostCount = myPostList.size();
        }

        //我收藏的贴
        List<MyPost> collectRecords = myPostCollectService.getCollectRecordsByUserId(currentUser.getUserId());
        int myCollectBBSPostCount = 0;
        if (!CollectionUtils.isEmpty(collectRecords)) {
            myCollectBBSPostCount = collectRecords.size();
        }

        request.setAttribute("myPostList", myPostList);
        request.setAttribute("myPostCount", myBBSPostCount);
        request.setAttribute("collectRecords", collectRecords);
        request.setAttribute("myCollectPostCount", myCollectBBSPostCount);
        request.setAttribute("myUser", currentUser);
        return "user/index";
    }

    @PostMapping("/updateUserInfo")
    @ResponseBody
    public Result updateInfo(@RequestParam("nickName") String nickName,
                             @RequestParam("userGender") int userGender,
                             @RequestParam("location") String location,
                             @RequestParam("introduce") String introduce,
                             HttpSession httpSession) {

        if (!StringUtils.hasLength(nickName)) {
            return ResultGenerator.genFailResult("nickName参数错误");
        }
        if (userGender < 1 || userGender > 2) {
            return ResultGenerator.genFailResult("userGender参数错误");
        }
        if (!StringUtils.hasLength(location)) {
            return ResultGenerator.genFailResult("location参数错误");
        }
        if (!StringUtils.hasLength(introduce)) {
            return ResultGenerator.genFailResult("introduce参数错误");
        }
        MyUser myUser = (MyUser) httpSession.getAttribute(Constants.USER_SESSION_KEY);
        myUser.setNickName(nickName);
        if (userGender == 1) {
            myUser.setGender("男");
        }
        if (userGender == 2) {
            myUser.setGender("女");
        }
        myUser.setLocation(location);
        myUser.setIntroduce(introduce);
        if (myUserService.updateUserInfo(myUser, httpSession)) {
            Result result = ResultGenerator.genSuccessResult();
            return result;
        } else {
            Result result = ResultGenerator.genFailResult("修改失败");
            return result;
        }
    }

    @PostMapping("/updateHeadImg")
    @ResponseBody
    public Result updateHeadImg(@RequestParam("userHeadImg") String userHeadImg,
                                HttpSession httpSession) {

        if (!StringUtils.hasLength(userHeadImg)) {
            return ResultGenerator.genFailResult("userHeadImg参数错误");
        }
        MyUser myUser = (MyUser) httpSession.getAttribute(Constants.USER_SESSION_KEY);
        myUser.setHeadImgUrl(userHeadImg);
        if (myUserService.updateUserHeadImg(myUser, httpSession)) {
            Result result = ResultGenerator.genSuccessResult();
            return result;
        } else {
            Result result = ResultGenerator.genFailResult("修改失败");
            return result;
        }
    }

    @PostMapping("/updatePassword")
    @ResponseBody
    public Result passwordUpdate(HttpServletRequest request, @RequestParam("originalPassword") String originalPassword,
                                 @RequestParam("newPassword") String newPassword) {
        if (!StringUtils.hasLength(originalPassword) || !StringUtils.hasLength(newPassword)) {
            return ResultGenerator.genFailResult("参数不能为空");
        }
        MyUser currentUser = (MyUser) request.getSession().getAttribute(Constants.USER_SESSION_KEY);
        if (myUserService.updatePassword(currentUser.getUserId(), originalPassword, newPassword)) {
            //修改成功后清空session中的数据，前端控制跳转至登录页
            request.getSession().removeAttribute(Constants.USER_SESSION_KEY);
            return ResultGenerator.genSuccessResult();
        } else {
            return ResultGenerator.genFailResult("修改失败");
        }
    }

    @GetMapping("/logout")
    public String logout(HttpSession httpSession) {
        httpSession.removeAttribute(Constants.USER_SESSION_KEY);
        httpSession.removeAttribute(Constants.USER_ROLE);
        return "user/login";
    }

    @PostMapping("/register")
    @ResponseBody
    public Result register(@RequestParam("loginName") String loginName,
                           @RequestParam("verifyCode") String verifyCode,
                           @RequestParam("nickName") String nickName,
                           @RequestParam("password") String password,
                           @RequestParam("mailCode") String mailCode,
                           HttpSession httpSession) {
        if (!StringUtils.hasLength(loginName)) {
            return ResultGenerator.genFailResult(ServiceResultEnum.LOGIN_NAME_NULL.getResult());
        }
        if (!PatternUtil.isEmail(loginName)) {
            return ResultGenerator.genFailResult(ServiceResultEnum.LOGIN_NAME_NOT_EMAIL.getResult());
        }
        if (!StringUtils.hasLength(password)) {
            return ResultGenerator.genFailResult(ServiceResultEnum.LOGIN_PASSWORD_NULL.getResult());
        }
        if (!StringUtils.hasLength(verifyCode)) {
            return ResultGenerator.genFailResult(ServiceResultEnum.LOGIN_VERIFY_CODE_NULL.getResult());
        }
        String myEmailCode = httpSession.getAttribute(Constants.EMAIL_CODE) + "";
        if(!StringUtils.hasLength(mailCode) || !mailCode.equals(myEmailCode)){
            return ResultGenerator.genFailResult(ServiceResultEnum.EMAIL_ERROR.getResult());
        }
            String kaptchaCode = httpSession.getAttribute(Constants.VERIFY_CODE_KEY) + "";
        if (!StringUtils.hasLength(kaptchaCode) || !verifyCode.equals(kaptchaCode)) {
            return ResultGenerator.genFailResult(ServiceResultEnum.LOGIN_VERIFY_CODE_ERROR.getResult());
        }
        String registerResult = myUserService.register(loginName, password, nickName, httpSession);
        //注册成功
        if (ServiceResultEnum.SUCCESS.getResult().equals(registerResult)) {
            //删除session中的验证码
            httpSession.removeAttribute(Constants.VERIFY_CODE_KEY);
            httpSession.removeAttribute(Constants.EMAIL_CODE);
            return ResultGenerator.genSuccessResult();
        }
        //注册失败
        return ResultGenerator.genFailResult(registerResult);
    }


    @PostMapping("/login")
    @ResponseBody
    public Result login(@RequestParam("loginName") String loginName,
                        @RequestParam("verifyCode") String verifyCode,
                        @RequestParam("password") String password,
                        HttpSession httpSession) {
        if (!StringUtils.hasLength(loginName)) {
            return ResultGenerator.genFailResult(ServiceResultEnum.LOGIN_NAME_NULL.getResult());
        }
        if (!PatternUtil.isEmail(loginName)) {
            return ResultGenerator.genFailResult(ServiceResultEnum.LOGIN_NAME_NOT_EMAIL.getResult());
        }
        if (!StringUtils.hasLength(password)) {
            return ResultGenerator.genFailResult(ServiceResultEnum.LOGIN_PASSWORD_NULL.getResult());
        }
        if (!StringUtils.hasLength(verifyCode)) {
            return ResultGenerator.genFailResult(ServiceResultEnum.LOGIN_VERIFY_CODE_NULL.getResult());
        }
        String kaptchaCode = httpSession.getAttribute(Constants.VERIFY_CODE_KEY) + "";
        if (!StringUtils.hasLength(kaptchaCode) || !verifyCode.equals(kaptchaCode)) {
            return ResultGenerator.genFailResult(ServiceResultEnum.LOGIN_VERIFY_CODE_ERROR.getResult());
        }
        String loginResult = myUserService.login(loginName, MD5Util.MD5Encode(password, "UTF-8"), httpSession);
        //登录成功
        if (ServiceResultEnum.SUCCESS.getResult().equals(loginResult)) {
            //删除session中的验证码
            httpSession.removeAttribute(Constants.VERIFY_CODE_KEY);
            return ResultGenerator.genSuccessResult();
        }
        //登录失败
        return ResultGenerator.genFailResult(loginResult);
    }

    @PostMapping("/getEmailCode")
    @ResponseBody
    public Result getEmailCode(@RequestParam("loginName")String loginName,
                               @RequestParam("verifyCode")String verifyCode,
                               HttpSession httpSession){

        String kaptchaCode = httpSession.getAttribute(Constants.VERIFY_CODE_KEY) + "";
        if (!StringUtils.hasLength(kaptchaCode) || !verifyCode.equals(kaptchaCode)) {
            return ResultGenerator.genFailResult(ServiceResultEnum.LOGIN_VERIFY_CODE_ERROR.getResult());
        }
        return emailService.sendMail(loginName, httpSession);
    }

    @PostMapping("/userBanned")
    @ResponseBody
    public Result userBanned(MyUser myUser, HttpSession session){
        try {
            if(myUserService.bannedUser(myUser, session) > 0){
                return ResultGenerator.genSuccessResult();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResultGenerator.genFailResult("封号失败！");
    }
    @PostMapping("/unBannedUser")
    @ResponseBody
    public Result unBannedUser(MyUser myUser){
        try {
            myUserService.unBannedUser(myUser);
            return ResultGenerator.genSuccessResult();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResultGenerator.genFailResult("解封失败！");
    }

    @GetMapping("/getBannedUser")
    public String getBannedUser(HttpServletRequest request,
                                @RequestParam(value = "page", required = false, defaultValue = "1") Integer pageNumber,
                                @RequestParam(value = "keyword", required = false) String keyword){
        //封装参数
        Map<String, Object> params = new HashMap<>(5);
        params.put("page", pageNumber);
        //默认每页10条
        params.put("limit", 10);

        //搜索关键字
        if (StringUtils.hasLength(keyword)) {
            request.setAttribute("keyword", keyword);
            params.put("keyword", keyword);
        }

        PageQueryUtil pageUtil = new PageQueryUtil(params);
        PageResult pageBannedUser = myUserService.getPageBannedUser(pageUtil);

        request.setAttribute("pageResult", pageBannedUser);
        return "admin/userBlackHome";
    }

}
